import pymongo
import gridfs
import bson
import time
from config import *
conn = pymongo.Connection(host=MONGO_HOST,port=MONGO_PORT)
mongo = conn.filestore
filesys = gridfs.GridFS(mongo)


class FileStore:
    def __init__(self):
        pass
    
    def file_exists(self,**arg):
        if(arg.has_key("filename")):
            ret = filesys.exists({"filename": arg['filename']})
        elif(arg.has_key("fileid")):
            ret = filesys.exists(arg['fileid'])
        else:
            ret = None
        return ret
    
    def put(self,file_content,filename):
        ret = filesys.put(file_content,filename=filename)
        if(ret):
            return str(ret)
        return ret
    
    def get(self,fileid):
        fileid = bson.ObjectId(fileid)
        ret = filesys.get(fileid).read()
        return ret
    
    def delete(self,fileid):
        ret = filesys.delete(fileid)
        return ret
    
    def get_objid_by_name(self,filename):
        tb = mongo.fs.files
        info = tb.find_one({"filename":filename})
        if(info):
            return str(info["_id"])
        else:
            return None
        